package ua.races.servlet;

import org.apache.log4j.Logger;
import ua.races.command.ServletCommand;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class SecurityFilter implements Filter {
    private static final Logger log = Logger.getLogger(SecurityFilter.class.getName());
    ServletContext servletContext = null;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        servletContext = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        final HttpServletRequest req = (HttpServletRequest) request;
        final HttpServletResponse resp = (HttpServletResponse) response;
        String[] urls = {
                "/index.jsp", "/staffEntry.jsp", "/logout.do", "/staffCheck.do", "/clientCheck.do", "/"
        };


        if (    //TODO normal array comparation
                !Boolean.TRUE.equals(req.getSession(true).getAttribute(ServletCommand.SESS_AUTH)) &&
                        !(Arrays.asList(urls).contains(req.getRequestURI())
//                                req.getRequestURI().equals("/index.jsp") || req.getRequestURI().equals("/clientCheck.do") ||
//                                        req.getRequestURI().equals("/staffEntry.jsp") || req.getRequestURI().equals("/staffCheck.do") ||
//                                        req.getRequestURI().equals("/logout.do") || req.getRequestURI().equals("/")
                        )
                ) {
            req.setAttribute("message", "You are not authorized! Please login!");
            if (req.getRequestURI().matches("admin") || req.getRequestURI().matches("bookmaker")) {
                req.setAttribute("URL", "staffEntry.jsp");
            } else {
                req.setAttribute("URL", "index.jsp");
            }
            servletContext.getRequestDispatcher("/redirection.jsp").forward(req, resp);

            return;
        }
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
